package repository

import (
	"context"

	"github.com/ecodeclub/ekit/slice"

	"gitee.com/flycash/simple-im/internal/domain"
	"gitee.com/flycash/simple-im/internal/repository/dao"
)

type MessageRepository interface {
	SaveMessage(ctx context.Context, msg domain.Message) (int64, error)
	GetHistoryMessages(ctx context.Context, cid int64, lastMsgID int64, offset, limit int) ([]domain.Message, error)
}

type messageRepository struct {
	dao dao.MessageDAO
}

func NewMessageRepository(d dao.MessageDAO) MessageRepository {
	return &messageRepository{dao: d}
}

func (r *messageRepository) GetHistoryMessages(ctx context.Context, cid, lastMsgID int64, offset, limit int) ([]domain.Message, error) {
	list, err := r.dao.GetHistoryMessages(ctx, cid, lastMsgID, offset, limit)
	if err != nil {
		return nil, err
	}
	return slice.Map(list, func(_ int, src dao.Message) domain.Message {
		return r.toDomain(src)
	}), nil
}

func (r *messageRepository) SaveMessage(ctx context.Context, msg domain.Message) (int64, error) {
	entity := r.domainToEntity(msg)
	return r.dao.Insert(ctx, entity)
}

func (r *messageRepository) domainToEntity(msg domain.Message) dao.Message {
	return dao.Message{
		Key:         msg.Key,
		ContentType: msg.ContentType,
		Content:     msg.Content,
		SendID:      msg.Sender,
		SendTime:    msg.SendTime,
		Cid:         msg.Cid,
	}
}

func (r *messageRepository) toDomain(msg dao.Message) domain.Message {
	return domain.Message{
		ID:          msg.ID,
		Key:         msg.Key,
		ContentType: msg.ContentType,
		Content:     msg.Content,
		Sender:      msg.SendID,
		SendTime:    msg.SendTime,
		Cid:         msg.Cid,
	}
}
